<script setup lang="ts">
import type { Ref } from 'vue'
import type { ComponentOptions } from '@/components/LayoutForm/src/componentPanel/index'
import { inject, ref } from 'vue'
import CodeMirrorEditor from '../../codeMirrorEditor/index.vue'
import Gadialog from '../../components/GaDialog/index.vue'

const selectComponent = inject('selectComponent') as Ref<ComponentOptions>

const dialogVisible = ref(false)
const activeIndex = ref<number>(0)

const code = ref<string>('')

function handleClick(index: number) {
  activeIndex.value = index
  code.value = selectComponent.value.event[activeIndex.value].code || ''
}
watch(code, (newVal) => {
  selectComponent.value.event[activeIndex.value].code = newVal
})
function onOpen() {
  dialogVisible.value = true
  if (selectComponent.value.event || selectComponent.value.event?.length > 0) {
    code.value = selectComponent.value.event[activeIndex.value].code || ''
  }
  else {
    code.value = ''
  }
}
</script>

<template>
  <ElButton class=" w-full" plain type="primary" size="small" @click="onOpen">
    去设置
  </ElButton>
  <Gadialog v-model="dialogVisible" title="事件配置" width="50%">
    <ElContainer>
      <ElAside width="200px" class=" h-[50vh]">
        <div
          v-for="(item, index) in selectComponent.event || []"
          :key="index" :class="{ 'bg-[--el-color-primary-light-9]': activeIndex === index }"
          class=" border border-solid border-gray-300 rounded mr-[20px] p-[5px] cursor-pointer hover:bg-gray-100 mb-[5px]"
          @click="handleClick(index)"
        >
          <div class=" text-[14px] font-medium">
            {{ item.name }}
          </div>
          <div class=" text-[12px] text-gray-500">
            {{ item.des }}
          </div>
        </div>
        <ElEmpty v-if="!selectComponent.event || selectComponent.event.length === 0" description="暂无事件" />
      </ElAside>
      <ElMain class=" border border-solid border-gray-300">
        <CodeMirrorEditor v-model="code" :dark="true" :auto-destroy="true" :code-style="{ height: '50vh' }" />
      </ElMain>
    </ElContainer>
  </Gadialog>
</template>
